/**
* @package Scribble
*/
$(document).ready(function() {

	// Focus input on "page name" field
	$('#page-name').focus();

	// Add handler to parent-selector
	$('select[name=page_id]').change(parentChanged);
	parentChanged();

	// Add focus handlers to url-options
	$('#url-options input[type=text]').click(function() {
		$(this).parents('dd').find('input[type=radio]').attr('checked', true);
	});

	// Init auto-url previewer
	$('input[name=title]').keyup(updateAutoUrlPreview);
	updateAutoUrlPreview();

	// Init publish date picker
	if($('#fe-datepublish').size()>0) {
		$('#fe-datepublish').datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: 'dd/mm/yy',
			duration: '',
			onSelect: function(d, el) {
				d = d.replace(/^0/, '').replace(/\/0/, '/').split('/');
				$('#fe-dateexpire').datepicker('option', 'minDate', new Date(d[2], parseInt(d[1])-1, parseInt(d[0])+1));
			}
		});
	}

	// Init expiry date picker
	if($('#fe-datepublish').size()>0) {
		var d = $('#fe-datepublish').val().replace(/^0/, '').replace(/\/0/, '/').split('/');
		$('#fe-dateexpire').datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: 'dd/mm/yy',
			duration: '',
			minDate: new Date(d[2], parseInt(d[1])-1, parseInt(d[0])+1)
		});
	}

	// Add confirmation to "delete" button
	$('button[rel=page-delete]').attr('disabled', '').click(function() {
		return confirm("Are you sure you want to remove this page?");
	});
});

/**
* Performs a few actions when the parent page is changed.
*
* @return void
*/
function parentChanged(el) {
	var parentId = $('select[name=page_id]').val();
	if(parentId=='' || $('select[name=page_id]').size()==0) {
		$('#menuslot-options div.menuslot-option-sub').addClass('disabled').find('input').attr('checked', '');
	}
	else {
		$('#menuslot-options div.menuslot-option-sub').removeClass('disabled');
	}
}

/**
* Updates the auto-url preview based on the current page title.
*
* @return void
*/
function updateAutoUrlPreview() {

	// Convert page title into a valid url
	var title = $('input[name=title]').val().replace(/[^a-z0-9]/ig, '-').replace(/\-+/g, '-').replace(/\-$/, '').toLowerCase();
	$('#auto-url-preview').val(title);
}